package com.bulk.url;

import cn.hutool.json.JSONUtil;
import com.linkedin.urls.Url;
import com.linkedin.urls.detection.UrlDetector;
import com.linkedin.urls.detection.UrlDetectorOptions;

import java.util.List;

/**
 * 识别文本中的 url
 *
 * @author 散装java
 * @date 2022-12-27
 */
public class Detector {

    public static void main(String[] args) {
//        String text = "上海出发双动霞浦\n" +
//                "体验秋冬看海的浪漫~\n" +
//                "体验山海画境，行摄霞浦！\n" +
//                "\n" +
//                "H:t=预售###https://tuniu.cc/t/RKKVN8?name=张三\n";
        String text = "\uD83C\uDFD6️开启\uD83D\uDD1B海南度假模式\n" +
                "\uD83C\uDF89绝美西岛 新品上市\n" +
                "\uD83D\uDCB0剑麻酒店2晚498起含早\n" +
                "\uD83D\uDCF7赠价值699双人专业旅拍➕\n" +
                "     度假区无限畅玩\n" +
                "\uD83C\uDFAB超长有效期，快来囤货～\n" +
                "\uD83D\uDC49! tuniu.cc/t/pvSLwu";
        String oldStr = text;
        // 中文正则 代码里面首先把中文都变成空格了，防止中文与英文网址在一起被错误识别
        String REGEX_CHINESE = "[\u4e00-\u9fa5]";
        // 正则 emoji, 替换 emoji 防止对匹配结果产生影响
        String REGEX_EMOJI = "[\ud800\udc00-\udbff\udfff\ud800-\udfff]";
        text = text.replaceAll(REGEX_CHINESE, " ");
        text = text.replaceAll(REGEX_EMOJI, " ");
        text = text.replaceAll("：",":");
        System.out.println("replace text: " + text);

        UrlDetector parser = new UrlDetector(text, UrlDetectorOptions.Default);
        List<Url> found = parser.detect();
        System.out.println("urlList = " + JSONUtil.toJsonStr(found));
        System.out.println("url = " + found.get(0).getOriginalUrl());
        System.out.println("text = \n" + text);
        System.out.println("oldStr = \n" + oldStr);
        // 替换文本中的http请求
        String fixStr = oldStr.replace(found.get(0).getOriginalUrl(), "http://tuniu.cc/t/666");
        System.out.println("fixStr = \n" + fixStr);
        System.out.println("text = \n" + text);
        System.out.println("oldStr = \n" + oldStr);

        UrlDetector urlDetector = new UrlDetector("戳:tuniu.cc/t/wi0w4p", UrlDetectorOptions.Default);
        List<Url> urls = urlDetector.detect();
        System.out.println("ll = " + urls.get(0).getOriginalUrl());
    }
}
